package org.crl.blogsystem.service;

import cn.dev33.satoken.stp.StpUtil;
import org.crl.blogsystem.entity.Blog;
import org.crl.blogsystem.entity.Comment;
import org.crl.blogsystem.entity.User;
import org.crl.blogsystem.entity.dto.CommentDTO;
import org.crl.blogsystem.repository.CommentRespository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CommentService implements ICommentService{
    @Autowired
    CommentRespository commentRespository;

    @Autowired
    BlogService blogService;

    @Autowired
    UserService userService;

    @Override
    public Comment add(Long blogId,CommentDTO commentDTO) {
        User user = userService.getById(StpUtil.getLoginIdAsLong());
        Blog blog = blogService.getById(blogId);
        blog.setCommentsCount(blog.getCommentsCount()  == null ? 1 :blog.getCommentsCount() + 1);
        blogService.save(blog);
        Comment comment = new Comment();
        comment.setContent(commentDTO.getContent());
        comment.setUser(user);
        comment.setBlog(blog);
        comment.setCreatedAt(LocalDateTime.now());
        return commentRespository.save(comment);
    }

    @Override
    public void delete(Long id) {
        Comment comment = commentRespository.findById(id).orElseThrow();
        Blog blog = comment.getBlog();
        blog.setCommentsCount(blog.getCommentsCount()  == null ? 1 : blog.getCommentsCount() - 1);
        blogService.save(blog);
        commentRespository.deleteById(id);
    }

    @Override
    public List<Comment> getListByBlogId(Long blogId) {
        List<Comment> commentList = commentRespository.findByBlogIdOrderByCreatedAtDesc(blogId);
        return commentList;
    }
}
